<template>
  <div class="xtx-numbox">
    <div class="label">数量</div>
    <div class="numbox">
      <!-- 减操作 -->
      <a @click="sub" href="javascript:;">-</a>
      <!-- 显示结果 -->
      <input type="text" readonly :value="num" />
      <!-- 加操作 -->
      <a @click="add" href="javascript:;">+</a>
    </div>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
export default {
  name: 'XtxNumbox',
  emits: ['update:modelValue'],
  props: {
    a: String,
    // 接收v-model数据
    // v2: value + @input
    // v3: modelValue + @update:modelValue
    modelValue: {
      type: Number,
      default: 1
    },
    min: {
      type: Number,
      default: 1
    },
    // 根据商品库存决定
    max: {
      type: Number,
      default: 10
    }
  },
  setup (props, { emit, attrs }) {
    console.log('没有接收的props:', attrs)
    const num = ref(1)
    // 加减逻辑
    function add () {
      if (props.max === num.value) return
      num.value++
      // 同步数据到v-model绑定变量=>子到父
      emit('update:modelValue', num.value)
    }
    function sub () {
      if (props.min === num.value) return
      num.value--
      // 同步数据到v-model绑定变量
      emit('update:modelValue', num.value)
    }
    // 父到子
    watch(() => props.modelValue, (newVal) => {
      num.value = newVal
    }, { immediate: true })
    return {
      num,
      add,
      sub
    }
  }
}
</script>
<style scoped lang="less">
.xtx-numbox {
  display: flex;
  align-items: center;
  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }
  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;
    > a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;
      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }
      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }
    > input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>
